package com.hkj.genealogy.genealogydemo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hkj.genealogy.genealogydemo.entity.Member;
import com.hkj.genealogy.genealogydemo.entity.MemberTree;
import com.hkj.genealogy.genealogydemo.entity.User;
import com.hkj.genealogy.genealogydemo.service.MemberServiceImp;
import com.hkj.genealogy.genealogydemo.service.MemberTreeServiceImp;
import com.hkj.genealogy.genealogydemo.service.UserServiceImp;
import com.hkj.genealogy.genealogydemo.util.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: genealogydemo
 * @description: 成员控制类
 * @author: Hekejian
 * @time: 2020-07-05 20:44
 **/
@Controller
public class MemberController {
    @Autowired
    MemberServiceImp memberServiceImp;
    @Autowired
    UserServiceImp userServiceImp;
    @Resource
    MemberTreeServiceImp memberTreeServiceImp;
    @RequestMapping("/addRoot")
    public String createRoot(Member member){
        if (memberServiceImp.createRoot(member)){
            return "redirect:/home";
        }
        return "failure";
    }

    @RequestMapping("/addChildren")
    public String addChildren(Member member){
        if(memberServiceImp.addChildren(member))
        return "redirect:/home";
        else return "failure";
    }

    @RequestMapping("/getGenealogy")
    @ResponseBody
    public String getGenealogy(Authentication authentication) throws JsonProcessingException {
        ObjectMapper objectMapper=new ObjectMapper();
        String name = authentication.getName();
        User userInfo = userServiceImp.getUserInfo(name);
        Long fid = userServiceImp.gerUserFid(userInfo.getId());
        List<MemberTree> members=memberTreeServiceImp.getMemberTree(fid);
        List<MemberTree> trees = TreeUtil.recursiveMemberTree(members);
        Map<String,Object> map=new HashMap<>();

        map.put("data",trees);
        return objectMapper.writeValueAsString(map);
    }
    @RequestMapping("/addAccount")
    public String addAccount(Member member){
        member.setPassword(new BCryptPasswordEncoder().encode(member.getPassword()));
        memberServiceImp.addAccount(member);
        return "redirect:home";
    }
}
